package com.itheima.handlerException;

import com.itheima.entity.Result;
import com.itheima.exception.BusinessRuntimeException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.servlet.ServletException;


@RestControllerAdvice
@Slf4j
public class MyHandlerException {


    /**
     * 处理权限不足时的错误 显示给前端 权限不足
     * @param e
     * @return
     */
    @ExceptionHandler({
            AccessDeniedException.class
    })
    @ResponseStatus(HttpStatus.OK)   //ResponseStarus响应状态码
    public Result chuli(AccessDeniedException e){
        log.debug("错误:"+e);
        return new Result(false,"权限不足！请重新登录或联系管理员！");
    }



    @ExceptionHandler({
            BusinessRuntimeException.class
    })
    @ResponseStatus(HttpStatus.OK)   //ResponseStarus响应状态码
    public Result chuli(BusinessRuntimeException e){
            return new Result(false,e.getMessage());
    }


    @ExceptionHandler({
            ServletException.class,              // mediaType不匹配、method不匹配……
            HttpMessageConversionException.class,//http body转换异常，@RequestBody的参数
            MethodArgumentNotValidException.class ,  //http请求缺少查询参数
            MethodArgumentTypeMismatchException.class//http请求参数类型不匹配
    })
    public String aa(Exception e) throws Exception {
        throw e;
    }


    @ExceptionHandler({
            Exception.class
    })
    @ResponseStatus(HttpStatus.OK)
    public Result chuli2(Exception e){
        log.debug("错误类型:"+e);
        return new Result(false,"操作失败");
    }


}
